import React, { Component } from 'react';
import { Card, message, Tabs, Icon } from 'antd';

import './style.less';

const { TabPane } = Tabs;

class TabsPage extends Component {
  constructor(props) {
    super(props);
    this.newTabIndex = 0;
    const panes = [
      {
        title: 'Tab1',
        content: 'Tab1',
        key: '1'
      },
      {
        title: 'Tab2',
        content: 'Tab2',
        key: '2'
      },
      {
        title: 'Tab3',
        content: 'Tab3',
        key: '3'
      }
    ];
    this.state = {
      activeKey: panes[0].key,
      panes
    }
  }

  render() {
    const { panes, activeKey } = this.state;
    return (
      <div className="pinlor-buttons">
        <Card title="Tab页签" className="pinlor-cards">
          <Tabs defaultActivieKey="1" onChange={this.handleCallback}>
            <TabPane tab="Tab1" key="1">欢迎登录pinlor后台管理系统</TabPane>
            <TabPane tab="Tab2" key="2">React是一个非常受欢迎的MVC框架</TabPane>
            <TabPane tab="Tab3" key="3">Vue是一个轻量级的MVC框架</TabPane>
          </Tabs>
        </Card>
        <Card title="带图标的Tab页签" className="pinlor-cards">
          <Tabs defaultActivieKey="1" onChange={this.handleCallback}>
            <TabPane tab={<span><Icon type="plus" />Tab1</span>} key="1">欢迎登录pinlor后台管理系统</TabPane>
            <TabPane tab={<span><Icon type="edit" />Tab2</span>} key="2">React是一个非常受欢迎的MVC框架</TabPane>
            <TabPane tab={<span><Icon type="delete" />Tab3</span>} key="3">Vue是一个轻量级的MVC框架</TabPane>
          </Tabs>
        </Card>
        <Card title="可以删除的Tab页签" className="pinlor-cards">
          <Tabs
            onChange={this.handleChange}
            onEdit={this.onEdit}
            activeKey={activeKey}
            type="editable-card"
          >
            {
              panes.map(item => {
                return <TabPane
                  tab={item.title}
                  key={item.key}>
                  {item.content}
                </TabPane>
              })
            }
          </Tabs>
        </Card>
      </div>
    )
  }

  handleCallback = key => {
    message.info('Hi, 您选择了页签：' + key);
  };

  handleChange = key => {
    this.setState({
      activeKey: key
    })
  };

  onEdit = (targetKey, action) => {
    this[action](targetKey);
  };

  add = () => {
    const panes = this.state.panes;
    const activeKey = `newTab${this.newTabIndex++}`;
    panes.push({ title: `New Tab${activeKey}`, content: 'Content of new Tab', key: activeKey });
    this.setState({ panes, activeKey });
  };

  remove = (targetKey) => {
    let activeKey = this.state.activeKey;
    let lastIndex = 0;
    this.state.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const panes = this.state.panes.filter(pane => pane.key !== targetKey);
    if (lastIndex >= 0 && activeKey === targetKey) {
      activeKey = panes[lastIndex].key;
    }
    this.setState({ panes, activeKey });
  }
}

export default TabsPage;
